# coding: utf-8


from flask import (
    render_template, redirect, url_for, flash, request,
    jsonify)
from flask_login import login_required
from sqlalchemy.exc import IntegrityError

from app import db
from app.products.brand_forms import BrandForm, BrandSearchForm

from . import product_bp
from .models import Brand, ProductTemplate


@product_bp.route('/brands', methods=['GET', 'POST'])
@login_required
def brand_list():
    """
    品牌列表
    :return:
    """
    search_form = BrandSearchForm(formdata=request.form or request.args)

    search_args = {
        key: value for key, value in search_form.data.items() if value
    }
    brand_query = Brand.generate_list_query_condition(search_args)

    pagination = brand_query.paginate(error_out=False)
    brands = pagination.items
    return render_template(
        'brand/brand_list.html',
        search_form=search_form,
        brands=brands,
        pagination=pagination,
        url_kwargs=search_args
    )


@product_bp.route('/add_brand', methods=['GET', 'POST'])
@login_required
def add_brand():
    """
    新增品牌
    :return:
    """
    form = BrandForm()

    if form.validate_on_submit():
        try:
            brand = Brand()
            form.populate_obj(brand)
            db.session.add(brand)
            db.session.flush()
        except IntegrityError:
            # 已经存在该品牌则直接返回成功
            pass
        flash('新增品牌成功')
        return redirect(url_for('product_bp.brand_list'))
    return render_template(
        "/brand/brand_add.html",
        form=form,
    )


@product_bp.route('/brands/<int:brand_id>', methods=['GET', 'POST'])
@login_required
def edit_brand(brand_id):
    """
    编辑品牌
    :param brand_id:
    :return:
    """

    brand = Brand.query.get_or_404(brand_id)
    if request.method == 'POST':
        form = BrandForm()
        # 产品类型id不可修改
        form.product_type_id.data = brand.product_type_id

        if form.validate_on_submit():
            if form.brand_name.data != brand.brand_name:
                existed_brand = Brand.get_by_args(
                    product_type_id=brand.product_type_id,
                    brand_name=form.brand_name.data
                )
                if existed_brand:
                    flash('已经存在同名品牌，编辑失败')
                    return redirect(url_for('product_bp.brand_list'))
                # 更新商品冗余的品牌名称
                ProductTemplate.query.filter(
                    ProductTemplate.brand_id == brand.id
                ).update(
                    dict(
                        brand=brand.brand_name
                    )
                )
            form.populate_obj(brand)
            db.session.add(brand)
            db.session.flush()
            flash('更新品牌成功')
            return redirect(url_for('product_bp.brand_list'))
        else:
            flash('编辑出错，请检查表单数据。')
            return redirect(url_for(
                'product_bp.edit_brand', brand_id=brand_id)
            )
    else:
        form = BrandForm(obj=brand, is_read_only=True)
        return render_template(
            "/brand/brand_info.html",
            form=form,
            brand_id=brand_id
        )


@product_bp.route('/ajax/brand/choices', methods=['POST'])
def ajax_brand_choices():
    """
    create by ld_wu 2018-01-04
    获取产品类下的品牌下来数据
    :return:
    """
    product_type_id = request.get_json().get('product_type_id')
    choices = [(0, '--请选择品牌--')]
    if product_type_id:
        choices += Brand.brand_choices(product_type_id)
    return jsonify(
        choices
    )
